import React, {useEffect, useState, useCallback, useRef} from 'react';
import {
  StyleSheet,
  View,
  Easing,
  Dimensions,
  Text,
  Animated,
} from 'react-native';

const DIMENSION = Dimensions.get('window');
const WINDOW_WIDTH = DIMENSION.width;
const WINDOW_HEIGHT = DIMENSION.height;

const TIME_SHORT = 1500;

let dismissTimmer = null;

const ToastView = ({message = '', time = TIME_SHORT, onDismiss}) => {
  const [msg, setMessage] = useState(message);

  const moveAnim = useRef(new Animated.Value(0));
  const opacityAnim = useRef(new Animated.Value(0));

  useEffect(() => {
    setMessage(message);
    clearTimeout(dismissTimmer);
    timingDismiss();
    return () => {
      clearTimeout(dismissTimmer);
    };
  }, [message]);

  useEffect(() => {
    animateMemo();
  }, []);

  const animateMemo = useCallback(() => {
    Animated.timing(opacityAnim.current, {
      toValue: 1,
      duration: 100,
      easing: Easing.linear,
    }).start();
  }, []);

  const timingDismiss = () => {
    dismissTimmer = setTimeout(() => {
      dismiss();
    }, time);
  };

  const dismiss = () => {
    Animated.timing(opacityAnim.current, {
      toValue: 0,
      duration: 100,
      easing: Easing.linear,
    }).start(onDismission);
  };

  const onDismission = () => {
    onDismiss && onDismiss();
  };

  return (
    <View style={styles.container} pointerEvents="none">
      <Animated.View
        style={[
          styles.textContainer,
          {bottom: moveAnim.current, opacity: opacityAnim.current},
        ]}>
        <Text style={styles.defaultText}>{msg}</Text>
      </Animated.View>
    </View>
  );
};

const styles = StyleSheet.create({
  textContainer: {
    backgroundColor: 'rgba(0,0,0,.6)',
    borderRadius: 8,
    padding: 10,
    maxWidth: WINDOW_WIDTH * 0.8,
    alignSelf: 'flex-end',
  },
  defaultText: {
    color: '#FFF',
    fontSize: 15,
  },
  container: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: WINDOW_HEIGHT / 2,
    flexDirection: 'row',
    justifyContent: 'center',
  },
});

export default ToastView;
